﻿using AutoMapper;
using AutoMapper.Internal.Mappers;
using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.WebAPI.Application.Command.StartCommand;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;

namespace IntelligentAgriculture.WebAPI.Application.CommandHandler.StartCommandHandler
{
    /// <summary>
    /// 期初列表数据导入CommandHandler
    /// </summary>
    public class StartImportCommandHandler : IRequestHandler<StartImportCommand, Results<IActionResult>>
    {
        private readonly IStartService _startService;
        private readonly IMapper _mapper;

        public StartImportCommandHandler(IStartService startService, IMapper mapper)
        {
            _startService = startService;
            _mapper = mapper;
        }

        public async Task<Results<IActionResult>> Handle(StartImportCommand request, CancellationToken cancellationToken)
        {
            // 读取文件内容
            MemoryStream memoryStream = new MemoryStream();
            //将传进来的文件拷贝到内存流中
            request.File.CopyTo(memoryStream);
            //通过内存流读取文件内容
            var list = await memoryStream.QueryAsync<StartImportInput>();

            // 转换为实体
            var costomer = _mapper.Map<List<StartImportInput>, List<Start>>(list.ToList());
            
                //批量添加
                await _startService.AddStartAsync(costomer);
            
           
            return Results<IActionResult>.DataResult(new OkObjectResult("导入成功"));
        }
    }
}
